package org.example.impl;

import org.example.constant.AuthConstants;
import org.example.factory.LoginStrategyFactory;
import org.example.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取请求类型
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
        if (!StringUtils.hasText(loginType)){
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }

        LoginStrategy loginStrategy = loginStrategyFactory.getLoginStrategy(loginType);

        return loginStrategy.realLogin(username);
    }
}
